/*
 * @Author: 游戏逻辑控制
 * @Date: 2020-05-21 09:32:30
 * @LastEditTime: 2021-04-19 15:27:55
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \jump\assets\script\game\GameScene.ts
 */

import { OverPanel } from "./OverPanel";
import { G } from "../G";
import { Stage } from "./stage/Stage";
import { PlayerDieEvent } from "../events/PlayerDieEvent";
import { PlayerJumpSuccessEvent } from "../events/PlayerJumpSuccessEvent";
import { Player } from "./stage/Player";

const {ccclass, property} = cc._decorator;

@ccclass
export class GameScene extends cc.Component {

    @property(Stage)
    private stage: Stage = null;
    @property(cc.Label)
    private scoreLabel = null;
    private score = 0;
    @property(OverPanel)
    private overPanel: OverPanel = null;
    private bgmAudioId = -1;
    @property({
        type: cc.AudioClip,
    })
    private gameOverAudio = null;
    private gameOverAudioId = -1;

    onLoad () {
        // 适配
        if(cc.sys.isMobile) {
            cc.find("Canvas").getComponent(cc.Canvas).fitHeight =false;
            cc.find("Canvas").getComponent(cc.Canvas).fitWidth = true;
        }
    }

    start () {
        this.addlisteners();
        this.startGame();
    }

    startGame() {
        // 初始化台阶
        this.stage.reset();
        // 游戏开始 添加触摸、键盘监听
        this.stage.enableTouch();
    }

    // 再来一次 事件
    onRestart() {
        cc.audioEngine.stopAll();
        this.overPanel.hide();
        cc.director.loadScene("game");
    }

    // 添加 跳跃成功 和 失败 事件监听
    addlisteners() {
        G.on(PlayerDieEvent.NAME, this.onOver, this);
        G.on(PlayerJumpSuccessEvent.NAME, this.onPlayerJumpSuccess, this);
    }

    // 停止自定义事件监听
    removeListeners() {
        G.off(PlayerDieEvent.NAME, this.onOver, this);
        G.off(PlayerJumpSuccessEvent.NAME, this.onPlayerJumpSuccess, this);
    }

    // 回调：跳跃成功
    onPlayerJumpSuccess(event: PlayerJumpSuccessEvent) {
        let score = event.score;
        this.addScore(score);
        this.stage.updateStage(()=>{
            this.stage.addBlock();
        });
    }

    // 回调：玩家失败
    onOver() {
        cc.audioEngine.stop(this.bgmAudioId);
        let pNode = cc.find("Canvas/stage/Player/rotateAnchor");
        pNode.angle = 0;
        cc.tween(pNode)
            .to(1, {angle: 90})
            .start();

        this.gameOverAudioId = cc.audioEngine.play(this.gameOverAudio, false, 1);

        // 取消监听 玩家操作
        this.stage.disableTouch();
        setTimeout(() => {
            this.overPanel.show(this.score, this.onRestart, this);
        }, 500);
    }

    addScore(s) {
        this.score += s;
        this.scoreLabel.string = this.score;
    }
}